<template>
    <div class="find-password-container">
        <div class="find-password-box">
            <div class="find-password-header">
                <img src="@/assets/img/logo.png" alt="logo" class="logo"/>
                <h2>找回密码</h2>
            </div>
            
            <el-form 
                ref="findPasswordFormRef"
                :model="findPasswordForm"
                :rules="formRules"
                class="find-password-form"
            >
                <el-form-item prop="email">
                    <el-input 
                        v-model="findPasswordForm.email"
                        placeholder="请输入注册邮箱"
                        prefix-icon="Message"
                    />
                </el-form-item>
                
                <el-form-item prop="verifyCode">
                    <div class="verify-code-container">
                        <el-input 
                            v-model="findPasswordForm.verifyCode"
                            placeholder="请输入验证码"
                            prefix-icon="Key"
                        />
                        <el-button 
                            type="primary" 
                            :disabled="isCountingDown"
                            @click="sendVerifyCode"
                        >
                            {{ countDownText }}
                        </el-button>
                    </div>
                </el-form-item>

                <el-form-item prop="newPassword">
                    <el-input 
                        v-model="findPasswordForm.newPassword"
                        type="password"
                        placeholder="请输入新密码"
                        prefix-icon="Lock"
                        show-password
                    />
                </el-form-item>
                
                <el-form-item prop="confirmPassword">
                    <el-input 
                        v-model="findPasswordForm.confirmPassword"
                        type="password"
                        placeholder="请确认新密码"
                        prefix-icon="Lock"
                        show-password
                    />
                </el-form-item>

                <el-form-item>
                    <el-button 
                        type="primary" 
                        class="submit-button"
                        :loading="loading"
                        @click="handleSubmit"
                    >重置密码</el-button>
                </el-form-item>

                <div class="back-to-login">
                    <el-link type="primary" @click="$router.push('/user/login')">返回登录</el-link>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Message, Lock, Key } from '@element-plus/icons-vue'
import {sendEmailCode,checkCode,updateUserInfo} from '@/api/user/user'
import { md5 } from 'js-md5'
const router = useRouter()
const findPasswordFormRef = ref(null)
const loading = ref(false)
const countDown = ref(0)
const isCountingDown = ref(false)
const countDownText = ref('发送验证码')

const findPasswordForm = ref({
    email: '',
    verifyCode: '',
    newPassword: '',
    confirmPassword: ''
})

// 表单验证规则
const formRules = {
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    verifyCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { len: 6, message: '验证码长度为 6 位', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== findPasswordForm.value.newPassword) {
                    callback(new Error('两次输入密码不一致!'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}

// 发送验证码
const sendVerifyCode = async () => {
    try {
        await findPasswordFormRef.value.validateField('email')
        if (!findPasswordForm.value.email) {
            ElMessage.warning('请输入邮箱地址')
            return
        }
        
        isCountingDown.value = true
        countDown.value = 60
        countDownText.value = `${countDown.value}s`
        
        const res = await sendEmailCode(findPasswordForm.value.email)
        if (res.code === 200) {
            ElMessage.success('验证码已发送，请查收邮件')
            
            const timer = setInterval(() => {
                countDown.value--
                countDownText.value = `${countDown.value}s`
                if (countDown.value <= 0) {
                    clearInterval(timer)
                    isCountingDown.value = false
                    countDownText.value = '发送验证码'
                }
            }, 1000)
        } else {
            isCountingDown.value = false
            countDown.value = 0
            countDownText.value = '发送验证码'
            throw new Error(res.message || '发送失败')
        }
    } catch (error) {
        isCountingDown.value = false
        countDown.value = 0
        countDownText.value = '发送验证码'
        console.error('发送验证码失败：', error)
        ElMessage.error(error.message || '发送验证码失败')
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!findPasswordFormRef.value) return
    
    await findPasswordFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                loading.value = true
                // TODO: 调用检验验证码接口
                 const res = await checkCode(
                    {
                        email:findPasswordForm.value.email,
                        code:findPasswordForm.value.verifyCode,
                        password:md5(findPasswordForm.value.confirmPassword)
                    }
                )
                if(res.code === 200){
                        ElMessage.success('密码重置成功')
                        router.push('/user/login')
                }
               
            } catch (error) {
                console.error('重置密码失败：', error)
                ElMessage.error('重置密码失败：' + error.message)
            } finally {
                loading.value = false
            }
        }
    })
}
</script>

<style scoped>
.find-password-container {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: linear-gradient(135deg, #1c92d2, #f2fcfe);
}

.find-password-box {
    width: 400px;
    padding: 40px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.find-password-header {
    text-align: center;
    margin-bottom: 30px;
}

.logo {
    width: 80px;
    margin-bottom: 16px;
}

.find-password-header h2 {
    font-size: 24px;
    color: #303133;
    margin: 0;
}

.find-password-form {
    margin-top: 30px;
}

.verify-code-container {
    display: flex;
    gap: 12px;
}

.verify-code-container .el-button {
    width: 120px;
}

.submit-button {
    width: 100%;
    padding: 12px 0;
}

.back-to-login {
    text-align: center;
    margin-top: 16px;
}

:deep(.el-input__wrapper) {
    padding: 1px 11px;
}

:deep(.el-input__inner) {
    height: 40px;
}
</style>